import xml.etree.ElementTree as et

# authen gtinlian
# email gtinlian@sina.com
# reforence https://libvirt.org/formatdomain.html

def _get_uuid():
    from uuid import uuid4
    return str(uuid4())

# 显示
class GraphisConfig:
    def __init__(self,type,lisent=1, address="localhost",password=None, port=-1,ref=None):
        self.ref = ref  # 指向xml的对象
        self.type = type  # 类型
        self.lisent = lisent # 监听
        self.address = address # 地址
        self.password = password # 密码
        self.port = port # 端口
        
class Memory:
    def __init(self, unint, size):
        self.unit = unint
        self.size = size

class StoreDevice:
    def __init__(self, _type, size, path):
        self.type = _type
        self.size = size
        self.path = path
        
class Domain:
    def __init__(self):
        self.domain_type = "kvm"
        self.id = _get_uuid()
        self.name = None
        self.title = ""
        self.description = ""
        self.graphics = []
        
    # 获取xml 方法
    def getXml(self):
        # 创建domain
        domain = et.Element('domain')
        domain.attrib['type'] = self.domain_type
        domain.attrib['id'] = self.id
        
        # 虚拟机名称
        name = et.SubElement(domain, "name")
        if self.name:
            name.text = self.name
        else:
            name.text = self._defaultName()
        
        # uuid
        uuid = et.SubElement(domain, "uuid")
        uuid.text = _get_uuid()
        
        # genid
        genid = et.SubElement(domain, "genid")
        genid.text = _get_uuid()
        
        # title
        title = et.SubElement(domain, "title")
        title.text = self.title
        
        # description
        description = et.SubElement(domain, "description")
        description.text = self.description
        
        #metadata
        metadata = et.SubElement(domain, "metadata")
        
        os = et.SubElement(domain, "os")
        os_type = et.SubElement(os, "type")
        os_type.text = "hvm"
        os_type = et.SubElement(os, "boot ")
        os_type.attrib["dev"] = "cdrom"
        
        vcpu = et.SubElement(domain, "vcpu")
        vcpu.attrib["placement"] = "static"
        vcpu.attrib["current"] = '1'
        vcpu.text = '2'
        
        memory = et.SubElement(domain, "memory")
        memory.attrib['unit']="MB"
        memory.text = '512'
        
        
        return et.tostring(domain,encoding='unicode')
    
    
    def _defaultName(self):
        from datetime import datetime  
        current = datetime.now()
        return  current.strftime('new_host_%Y_%m_%d_%H_%M_%S')
    


# 创建对象
domain = Domain()
        
print(domain.getXml())